#pragma once

#include<iostream>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

class tcpClient
{
  private:
    std::string serip;
    int serport;
    int sock;
  public:
  tcpClient(std::string _serip = "127.0.0.1",int _serport = 8080)
  :serip(_serip)
   ,serport(_serport)
  {}
  void initClient()
  {
     sock = socket(AF_INET,SOCK_STREAM,0);
     if(sock < 0)
     {
       std::cerr<<"sock error"<<std::endl;
       exit(1);       
     }
     struct sockaddr_in ser;
     ser.sin_family = AF_INET;
     ser.sin_port = htons(serport);
     ser.sin_addr.s_addr = inet_addr(serip.c_str());
   //链接服务器
     if(connect(sock,(struct sockaddr*)&ser,sizeof(ser)) < 0)
     {
       std::cerr<<"connect error"<<std::endl;

     }
  }
  void start()
  {
     char msg[128];
     while(true){
      //用read读,udp不能使用read
     std::cout<<"please enter#";
     fflush(stdout);
    //0是标准输入，从标准输入开始读
     ssize_t s = read(0,msg,sizeof(msg)-1);
     if(s > 0)
     {    
      msg[s-1] = 0;
      //发送给服务器
      send(sock,msg,sizeof(msg)-1,0);
      //接收服务器的信息
      ssize_t ss = recv(sock,msg,sizeof(msg)-1,0);
      if(ss > 0)
      {
        msg[ss] = 0;
        std::cout<<"server #"<<msg<<std::endl;
      }
   }

}
}
  ~tcpClient()
  {
    close(sock);
  }
};
